class NodesController < ApplicationController

  layout "kogukond"

  before_filter :authorize

  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @node_pages, @nodes = paginate :nodes, :per_page => 10, :conditions => ["community_id = ?", session[:community_id]]
  end

  def show
    @node = Node.find(params[:id])
    @facets = @node.facets
    @connections = Node.find_by_sql ["select n.name from nodes n, edges e where (n.id = e.source and e.target = ?) or (n.id = e.target and e.source = ?)", @node.id, @node.id]
    @groups = @node.groups
    session[:node_name] = @node.name
    session[:node_id] = @node.id
  end

  def show_google_map
    @node = Node.find(params[:id])
  end

  def new
    @node = Node.new
  end

  def create
    @node = Node.new(params[:node])
    @node.community_id = session[:community_id]

    if @node.address
      # Get Lat and Long from service to be used later for Google Maps
      server = XMLRPC::Client.new2('http://rpc.geocoder.us/service/xmlrpc')
      result = server.call2('geocode', @node.address)
      @node.lat  = result[1][0]['lat']
      @node.long = result[1][0]['long']
    end

    if @node.save
      flash[:notice] = 'Node was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @node = Node.find(params[:id])
  end

  def update
    @node = Node.find(params[:id])
    if @node.update_attributes(params[:node])
      flash[:notice] = 'Node was successfully updated.'
      redirect_to :action => 'show', :id => @node
    else
      render :action => 'edit'
    end
  end

  def destroy
    Node.find(params[:id]).destroy
    redirect_to :action => 'list'
  end

  def new_facet
    @facet = Facet.new
  end

  def create_facet
    @facet = Facet.new(params[:facet])
    @facet.node_id = session[:node_id]
    if @facet.save
      flash[:notice] = 'Facet was successfully created.'
      redirect_to :action => 'show', :id => @facet.node_id
    else
      render :action => 'new_facet'
    end
  end

  def list_facets
    @facets = Facet.find(:all, :conditions => ["node_id = ?", session[:node_id]])
  end

  def edit_facet
    @facet = Facet.find(params[:id])
  end

  def destroy_facet
    Facet.find(params[:id]).destroy
    redirect_to :action => 'show', :id => params[:node_id]
  end

  def update_facet
    @facet = Facet.find(params[:id])
    if @facet.update_attributes(params[:facet])
      flash[:notice] = 'Facet was successfully updated.'
      redirect_to :action => 'list_facets', :node_id => @facet.node_id
    else
      render :action => 'edit'
    end
  end

end

